package cn.jx.asc.controller;

import cn.jx.asc.common.enums.ResultStatus;
import cn.jx.asc.common.response.Result;
import cn.jx.asc.common.response.ResultUtils;
import cn.jx.asc.common.utils.JwtUtils;
import cn.jx.asc.common.utils.MD5Utils;
import cn.jx.asc.pojo.entity.User;
import cn.jx.asc.pojo.vo.ProfileInfoVO;
import cn.jx.asc.pojo.vo.RoleVO;
import cn.jx.asc.resource.FileUpload;
import cn.jx.asc.service.ProfileService;
import cn.jx.asc.service.UserService;
import cn.jx.asc.utils.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * 个人信息
 *
 * @author lhg
 */

@Api(value = "个人信息", tags = {"个人信息的相关接口"})
@RestController
@RequestMapping("/profile")
@Slf4j
public class ProfileController {

    @Autowired
    private ProfileService profileService;

    @Autowired
    private FileUpload fileUpload;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "查询个人信息", notes = "查询个人信息", httpMethod = "GET")
    @GetMapping("/queryInfo")
    public Result queryInfo() {

        String username = null;
                /* ProfileInfoVO用于传个人信息 */
        ProfileInfoVO infoVO = new ProfileInfoVO();
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipal()==null){
            ResultUtils.resultWithoutData(ResultStatus.NEED_LOGIN);
        }else {
            username = JwtUtils.getUsername(String.valueOf(subject.getPrincipal()));
        }
      username = JwtUtils.getUsername(String.valueOf(subject.getPrincipal()));

        if ( username == null){
            log.error("token错误");
        }
        User user = userService.queryUserByName(username);
        if (user != null) {
            setProfileInfoVO(infoVO , user);
            String roleName = null;
            RoleVO roleVO = profileService.queryRoleByUserId( user.getId() );
            if (roleVO != null) {
                roleName = roleVO.getName();

            }
            infoVO.setRoleName(roleName);
        }
        return ResultUtils.resultWithData(ResultStatus.SUCCESS,infoVO);
    }

    @ApiOperation(value = "修改基本信息", notes = "修改基本信息", httpMethod = "POST")
    @PostMapping("/modifyBasicInfo")
    public Result modifyBasicInfo(
            @ApiParam(name = "profileInfoVO", value = "待修改的用户信息对象", required = true)
            @RequestBody ProfileInfoVO profileInfoVO) {
        Subject subject = SecurityUtils.getSubject();
        String username = JwtUtils.getUsername(String.valueOf(subject.getPrincipal()));
        if ( username == null){
            log.error("token错误");
            return ResultUtils.resultWithoutData(ResultStatus.TOKEN_ERROR);
        }
        User user = userService.queryUserByName(username);
        if (!StringUtils.isEmpty(profileInfoVO.getUsername())) {
            final boolean isExist = userService.queryUsernameIsExist(profileInfoVO.getUsername());

            if (!isExist || username !=null) {
                user.setUsername(profileInfoVO.getUsername());
            } else {
                return ResultUtils.resultWithoutData(ResultStatus.USERNAME_EXISTS);
            }
        }

        if (!StringUtils.isEmpty(profileInfoVO.getRealname())) {
            user.setRealname(profileInfoVO.getRealname());
        }

        if (!StringUtils.isEmpty(profileInfoVO.getEmail())) {
            user.setEmail(profileInfoVO.getEmail());
        }

        if (!StringUtils.isEmpty(profileInfoVO.getTelephone())) {
            user.setTelephone(profileInfoVO.getTelephone());
        }

        if (profileInfoVO.getAge() != null) {
            user.setAge(profileInfoVO.getAge());
        }
        if (profileInfoVO.getSex() != null) {
            user.setSex(profileInfoVO.getSex());
        }

        user.setUpdatedTime(null);
        boolean result = profileService.modifyBasicInfo(user);
        if (!result) {
           return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }
        return ResultUtils.resultWithoutData(ResultStatus.SUCCESS);
    }


    @ApiOperation(value = "修改密码", notes = "修改密码", httpMethod = "POST")
    @PostMapping("/modifyPassword")
    public Result modifyPassword(
            @ApiParam(name = "oldPassword", value = "旧密码", required = true)
            @RequestParam String oldPassword,
            @ApiParam(name = "newPassword", value = "新密码", required = true)
            @RequestParam String newPassword,
            @ApiParam(name = "confirmPwd", value = "确认密码", required = true)
            @RequestParam String confirmPwd) {

        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword) || StringUtils.isBlank(confirmPwd)) {
            return ResultUtils.resultWithoutData(ResultStatus.NOT_PASSWORD);
        }
        if (!newPassword.equals(confirmPwd)) {
           return ResultUtils.resultWithoutData(ResultStatus.INSECURE_PASSWORD);
        }
        Subject subject = SecurityUtils.getSubject();
        String username = JwtUtils.getUsername(String.valueOf(subject.getPrincipal()));
        if ( username == null){
            log.error("token错误");
        }
        User user1 = userService.queryUserByName(username);

        String userId = null;
        if (user1 != null){
            userId = user1.getId();
        }

        User user = userService.queryUserById(userId);

        try {
            if (!(user.getPassword()).equals(MD5Utils.getMD5Str(oldPassword))) {
                return ResultUtils.resultWithoutData(ResultStatus.PASSWORD_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if ((MD5Utils.getMD5Str(newPassword)).equals(MD5Utils.getMD5Str(oldPassword))) {
                return ResultUtils.resultWithoutData(ResultStatus.INSECURE_PASSWORD);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            user.setPassword(MD5Utils.getMD5Str(newPassword));
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setUpdatedTime(null);
        Boolean result = profileService.modifyPassword(user);
        return ResultUtils.resultWithData(ResultStatus.SUCCESS,result);
    }

    @ApiOperation(value = "修改头像", notes = "修改头像", httpMethod = "POST")
    @PostMapping("/modifyAvatar")
    public Result modifyAvatar(
            @ApiParam(name = "file", value = "MultipartFile头像文件", required = true)
            @RequestParam("avatarfile") MultipartFile file) {

        /* 定义头像保存地址 */
        // String fileSpace = Contants.IMAGE_USER_FACE_LOCATION;
        final String fileSpace = fileUpload.getImageUserAvatarLocation();

        final User user = ShiroUtils.getUser();

        final String userId = user.getId();

        String uploadPathPrefix = File.separator + userId;

        if (file != null) {

            FileOutputStream fileOutputStream = null;
            try {
                String fileName = file.getOriginalFilename();

                if (StringUtils.isBlank(fileName)) {
                    String[] fileNameArr = fileName.split(" \\. ");

                    String suffix = fileNameArr[fileNameArr.length - 1];

                    /* 文件名称重组 */
                    String newFileName = "avatars" + userId + "." + suffix;

                    String finalAvatarPath = fileSpace + uploadPathPrefix + File.separator + newFileName;

                    /* web服务头像地址*/
                    uploadPathPrefix += ("/" + newFileName);

                    File outFile = new File(finalAvatarPath);

                    if (outFile.getParentFile() != null) {
                        boolean mkdirs = outFile.getParentFile().mkdirs();
                    }

                    fileOutputStream = new FileOutputStream(outFile);
                    InputStream inputStream = file.getInputStream();
                    IOUtils.copy(inputStream, fileOutputStream);

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.flush();
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            return ResultUtils.resultWithoutData(ResultStatus.FAILED);
        }

        String imageServerUrl = fileUpload.getImageServerUrl();

        String finalUserAvatarUser = imageServerUrl + uploadPathPrefix;

        user.setProfilePhoto(finalUserAvatarUser);
        user.setUpdatedTime(null);
        Boolean result = profileService.modifyAvatar(user);
        return ResultUtils.resultWithoutData(ResultStatus.SUCCESS);
    }
    @GetMapping("/needLogin")
    public Result needLogin(){
        return ResultUtils.resultWithoutData(ResultStatus.NEED_LOGIN);
    }

    @GetMapping("/unauthc")
    public Result unauthc(){
        return ResultUtils.resultWithoutData(ResultStatus.NOT_AUTHC);
    }

    static void setProfileInfoVO(ProfileInfoVO infoVO, User user) {
        infoVO.setId(user.getId());
        infoVO.setUsername(user.getUsername());
        infoVO.setRealname(user.getRealname());
        infoVO.setProfilePhoto(user.getProfilePhoto());
        infoVO.setAge(user.getAge());
        infoVO.setSex(user.getSex());
        infoVO.setEmail(user.getEmail());
        infoVO.setTelephone(user.getTelephone());
    }

}
